<template>
  <el-form :inline="true" :model="formInline">
    <div
      class="no-scrollbar"
      :style="{
        width: screenWidth + 'px',
        'max-height': props.tableHeight + 'px',
        'overflow-y': 'auto',
        'overflow-x': 'auto',
        'scrollbar-width': 'thin',
      }"
    >
      <!-- 使用 el-table 替换原生 table -->
      <el-table
        :data="props.formDataList"
        style="width: 100%"
        border
        stripe
        height="calc(100% - 75px)"
        ref="elTable"
        :summary-method="getSummaries"
        show-summary
      >
        <el-table-column type="index" label="序号" width="50" align="center" fixed />
        <el-table-column
          type="selection"
          width="40"
          align="center"
          @select="toggleSelect"
          @select-all="toggleSelectAll"
          fixed
        />
        <el-table-column
          v-for="(column, index) in columns"
          :key="column.prop || column.type"
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :align="column.align"
          :fixed="column.fixed"
          :readonly="column.readonly"
          show-overflow-tooltip
        >
          <template #default="scope">
            <template v-if="column.prop === 'wlbm'">
              <el-input
                class="inputClass"
                :value="scope.row.wlbm"
                :readonly="true"
                placeholder=""
                clearable
                @click.native="props.openWlbm(scope.$index)"
              ></el-input>
            </template>
            <template v-if="column.calculateFrom && column.type === 'input'">
              <el-input
                class="inputClass"
                v-model.number="scope.row[column.prop]"
                :placeholder="column.placeholder"
                @blur="
                  calculateRowAmount(
                    scope.row,
                    column.prop,
                    column.calculateFrom,
                    column.calculationType
                  );
                  // 动态更新计算结果到当前行对应的目标属性
                  scope.row[column.prop] = calculateRowAmount(
                    scope.row,
                    column.prop,
                    column.calculateFrom,
                    column.calculationType
                  );
                "
              ></el-input>
            </template>

            <template v-if="column.type !== 'input' && column.type !== 'button'">
              {{ scope.row[column.prop] }}
            </template>
            <template v-else-if="column.type === 'input'">
              <el-input
                class="inputClass"
                v-model="scope.row[column.prop]"
                :placeholder="column.placeholder"
              ></el-input>
            </template>
            <template v-else-if="column.type === 'button'">
              <el-button type="danger" @click="() => handleDelete(scope.$index)"
                >删除</el-button
              >
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-form>
</template>

<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
  PropType,
} from "vue";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElTable,
  TableColumnCtx,
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  FormRules,
  FormInstance,
} from "element-plus";
import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../axios/axiosInstance";
import { format } from "date-fns";

// 日期中文
import zhCn from "element-plus/dist/locale/zh-cn.mjs";

const screenWidth = ref(window.innerWidth);
const screenHeight = ref(null);
const dynamicHeight = ref(null);
const dynamicHeightYtfl = ref(null);
const formInline = ref([]);
const inputHeight = ref(200);
const formData = ref([]);
const selectAll = ref(false);
const dialogTableVisible5 = ref(false);

const props = defineProps({
  tableHeight: {
    type: Number,
    required: true,
  },
  columns: {
    type: Array,
    required: true,
  },
  addRow: {
    type: Function as PropType<(index?: number) => void>,
    required: true,
  },
  handleDeletes: {
    type: Function as PropType<(index: number) => void>,
    required: true,
  },
  formDataList: {
    type: Array,
    required: true,
  },
  openWlbm: {
    type: Function as PropType<(index: number) => void>,
    required: true,
  },
});

const handleDelete = (index: number) => {
  props.handleDeletes(index);
};
interface Product {
  id: string;
  bzsl: number;
  bzdj: number;
  bzje: number;
}
interface SummaryMethodProps<T = Product> {
  columns: TableColumnCtx<T>[];
  data: T[];
}

function calculateRowAmount(
  row: Product,
  targetProp: string | string[],
  calculationProperties: string[] | string,
  calculationType: "*" | "+" | "-" | "/"
) {
  // if (calculationProperties == "bzsl") {
  //   console.log(bzsl);
  //   return;
  // }
  // if (calculationProperties == "bzdj") {
  //   console.log(bzdj);
  //   return;
  // }
  if (!Array.isArray(calculationProperties))
    calculationProperties = [calculationProperties];
  if (!calculationType) calculationType = "*"; // 添加一个默认值

  let values = calculationProperties.map((p) => Number(row[p]));

  return performCalculation(values, calculationType);
}

function performCalculation(values: number[], calculationType: "*" | "+" | "-" | "/") {
  switch (calculationType) {
    case "*":
      return values.reduce((a, b) => a * b, 1);
    case "+":
      return values.reduce((a, b) => a + b, 0);
    case "-":
      return values.reduce((a, b) => a - b);
    case "/":
      return values[0] / values[1];
    default:
      throw new Error("Unsupported calculation type");
  }
}
const getDeleteRowData = () => {
  const selectedIndexes: any = [];

  // 找到已勾选行的索引
  props.formDataList.forEach((formData, index) => {
    if (formData.selected) {
      selectedIndexes.push(index);
    }
  });

  // 删除已勾选行
  for (let i = selectedIndexes.length - 1; i >= 0; i--) {
    props.formDataList.splice(selectedIndexes[i], 1);
  }

  // 如果没有剩余行数据，添加一行
  if (props.formDataList.length === 0) {
    props.addRow();
  }
  selectAll.value = false;
};
const toggleSelectAll = () => {
  for (const formData of props.formDataList) {
    formData.selected = selectAll.value === true;
  }
};
const toggleSelect = (row: any) => {
  row.selected = !row.selected;
};
</script>

<style scoped>
.table-value:hover {
  cursor: pointer;
  z-index: 11;
}
.sticky-header {
  position: sticky;
  top: -1px;
  background-color: #ddd;
  width: 100%;
}

.table-header {
  border: 1px solid #ccc;
  background: rgb(225, 225, 230);
  /* width: 50px; */
  z-index: 99;
}
table tr td {
  /* width: 50px; */
  /* width: 10vh; */
  height: 30px;
}

table {
  border-collapse: collapse;
  border: 1px solid #ccc;
  width: 100%;
}

input {
  border: 1px solid transparent;
}

td {
  border: 1px solid #ccc;
}
.no-scrollbar::-webkit-scrollbar {
  display: none;
}
.no-scrollbar {
  width: fit-content;
  max-width: 100%;
  overflow-x: auto;
  scrollbar-width: thin;
}
::v-deep .t_layout_page_item {
  background-color: #f7f7f7;
}
</style>
